package com.tron.nettychat.nettysocket;


import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 *  处理TextWebSocketFrame 文本帧
 */
@Sharable
public class TronTextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {


    private  TronChannelManager tronChannelManager;


    private final Logger log = LoggerFactory.getLogger(this.getClass());



    /**
     * 接收路径传参，重新请求地址。
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            log.info("url==========={}",request.uri());
            request.setUri("/websocket");
        }
        super.channelRead(ctx, msg);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {

        log.info("======收到消息======链接id：{}，消息内容：{}",ctx.channel().id().asLongText(),msg.text());

        //返回消息
        ctx.channel().writeAndFlush(new TextWebSocketFrame(msg.text()));
    }


    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        log.info("======链接建立了======链接id：{}",ctx.channel().id().asLongText());
        super.handlerAdded(ctx);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        log.info("======链接断开了======链接id：{}",ctx.channel().id().asLongText());
        super.handlerRemoved(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("======链接异常======链接id：{}",ctx.channel().id().asLongText());
        ctx.close();
    }
}
